/*
 * String.cpp
 *
 *  Created on: Oct 1, 2010
 *      Author: gabriel
 */

#include "String.h"

namespace Utility
{
	namespace str
	{
		StrMap explode ( std::string split , std::string data )
		{
			StrMap ret;
			int index = 0;

			if ( data.find ( split.c_str() , 0 ) == std::string::npos )
				ret[index] = data;
			else
			{
				size_t s_index = data.find ( split.c_str() , 0 );
				ret[index] = data.substr( 0 , s_index ).c_str();
				index++;
				s_index += split.length();

				while ( data.find( split.c_str() , s_index ) != std::string::npos )
				{
					size_t n_index = data.find( split.c_str() , s_index );
					ret[index] = data.substr( s_index , ( n_index - s_index ) ).c_str();
					s_index = n_index + split.length();
					index++;
				}

				ret[index] = data.substr( s_index , ( data.length() - s_index ) ).c_str();
			}

			return ret;
		}

		std::string implode ( std::string split , StrMap data )
		{
			std::string buffer;

			StrMap::const_iterator end = data.end();
			StrMap::const_iterator it = data.begin();
			while ( it != end )
			{
				buffer.append( it->second.c_str() );

				++it;

				if ( it != end )
					buffer.append( split.c_str() );
			}

			return buffer;
		}

		std::string replace ( std::string _source , std::string _old , std::string _new)
		{

			while ( _source.find( _old.c_str() , 0 ) != std::string::npos )
				_source.replace ( _source.find ( _old.c_str() ) , _old.size(), _new );

			return _source;
		}
	}
}
